package com.kou.dao;

import com.kou.pojo.Address;
import com.kou.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author SteinY
 * @create 2022-03-26 9:18
 * @description:
 */
public class AddressDaoImpl implements AddressDao {
    QueryRunner queryRunner = new QueryRunner();
    @Override
    public List<Address> findAll(String uid) {
        Connection connection = DataSourceUtil.getConnection();
        String sql= "select * from tb_address where uid = ? ";
        try {
            return queryRunner.query(connection,sql,new BeanListHandler<>(Address.class),uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void add(String uid, String name, String phone, String detail) {
        Connection connection = DataSourceUtil.getConnection();
        String sql = "insert into tb_address values (0,?,?,?,?,0)";
        Object[] params = {detail,name,phone,uid};
        try {
            queryRunner.update(connection,sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(String id)  {
        Connection connection = DataSourceUtil.getConnection();
        String sql = "delete from tb_address where id = ? ";
        try {
            queryRunner.update(connection,sql,Integer.parseInt(id));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(String id, String state, String name, String phone, String detail) {
        Connection connection = DataSourceUtil.getConnection();
        String  sql = "update tb_address set name = ?,detail = ? , phone =  ? ,state = ? where id = ?";
        Object params[] = {name,detail,phone,state,id};
        try {
            queryRunner.update(connection,sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setDefault(String id) {
        Connection connection = DataSourceUtil.getConnection();
        String sql1="update tb_address set state = 0 where state = 1";
        String  sql2 = "update tb_address set state = 1 where id = ?";
        try {
            queryRunner.update(connection,sql1);
            queryRunner.update(connection,sql2,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
